// 统一服务管理器
use std::sync::Arc;
use tokio::sync::RwLock;
use anyhow::Result;
use tracing::{info, warn, error};

use codegraph_core::GraphSystem;
// 注意：这些类型可能不存在，我们需要创建简化版本
// use codegraph_graph::GraphEngine;
// use codegraph_parser::ParserRegistry;
// use codegraph_analytics::AnalyticsEngine;

use crate::error::AppError;

/// 服务状态
#[derive(Debug, Clone, PartialEq)]
pub enum ServiceStatus {
    Stopped,
    Starting,
    Running,
    Stopping,
    Error(String),
}

/// 统一服务管理器
pub struct ServiceManager {
    /// CodeGraph 核心系统
    graph_system: Arc<RwLock<Option<GraphSystem>>>,
    /// 服务状态
    status: Arc<RwLock<ServiceStatus>>,
}

impl ServiceManager {
    /// 创建新的服务管理器
    pub fn new() -> Self {
        Self {
            graph_system: Arc::new(RwLock::new(None)),
            status: Arc::new(RwLock::new(ServiceStatus::Stopped)),
        }
    }

    /// 初始化所有服务
    pub async fn initialize(&self) -> Result<(), AppError> {
        tracing::info!("Initializing service manager...");

        // 设置状态为启动中
        *self.status.write().await = ServiceStatus::Starting;

        // 初始化核心系统
        match self.initialize_graph_system().await {
            Ok(_) => tracing::info!("Graph system initialized successfully"),
            Err(e) => {
                tracing::error!("Failed to initialize graph system: {}", e);
                *self.status.write().await = ServiceStatus::Error(e.to_string());
                return Err(AppError::service_initialization(e.to_string()));
            }
        }

        // 设置状态为运行中
        *self.status.write().await = ServiceStatus::Running;
        tracing::info!("Service manager initialized successfully");

        Ok(())
    }

    /// 初始化核心系统
    async fn initialize_graph_system(&self) -> Result<()> {
        let system = GraphSystem::new().await?;
        *self.graph_system.write().await = Some(system);
        Ok(())
    }

    /// 关闭所有服务
    pub async fn shutdown(&self) -> Result<(), AppError> {
        tracing::info!("Shutting down service manager...");

        // 设置状态为停止中
        *self.status.write().await = ServiceStatus::Stopping;

        // 关闭核心系统
        if let Some(_system) = self.graph_system.write().await.take() {
            tracing::info!("Graph system shut down");
        }

        // 设置状态为已停止
        *self.status.write().await = ServiceStatus::Stopped;
        tracing::info!("Service manager shut down successfully");

        Ok(())
    }

    /// 获取服务状态
    pub async fn get_status(&self) -> ServiceStatus {
        self.status.read().await.clone()
    }

    /// 获取图系统引用
    pub fn get_graph_system(&self) -> Arc<RwLock<Option<GraphSystem>>> {
        self.graph_system.clone()
    }

    /// 检查服务健康状态
    pub async fn health_check(&self) -> Result<bool, AppError> {
        let status = self.get_status().await;

        match status {
            ServiceStatus::Running => {
                // 检查核心服务是否正常
                let graph_system_ok = self.graph_system.read().await.is_some();
                Ok(graph_system_ok)
            }
            _ => Ok(false)
        }
    }

    /// 重启服务
    pub async fn restart(&self) -> Result<(), AppError> {
        tracing::info!("Restarting service manager...");

        // 先关闭
        self.shutdown().await?;

        // 等待一小段时间
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

        // 重新初始化
        self.initialize().await?;

        tracing::info!("Service manager restarted successfully");
        Ok(())
    }
}

impl Default for ServiceManager {
    fn default() -> Self {
        Self::new()
    }
}

// 全局服务管理器实例
lazy_static::lazy_static! {
    pub static ref GLOBAL_SERVICE_MANAGER: ServiceManager = ServiceManager::new();
}

/// 获取全局服务管理器
pub fn get_service_manager() -> &'static ServiceManager {
    &GLOBAL_SERVICE_MANAGER
}
